# -*- coding: utf-8 -*-
'''
Created on 21 mars 2011

@author: thierry
'''


from mod_python import apache
from mod_python import util
from mod_python import Session

LOGGUED_USER_KEY = 'LOGGUED_USER'


def logout(req):
    session = Session.Session(req, lock=0)
    if not session.is_new():
        req.log_error("existing session found", apache.APLOG_DEBUG)           
        session.invalidate()
        req.log_error("existing session invalidated", apache.APLOG_INFO)           
    else:
        req.log_error("new session, do not need to invalidate", apache.APLOG_INFO)   
        
def init_session(session):
    session.set_timeout(60*5)
    session.save()

def getLoguedUser(req):
    """
    Check if an user is authenticated then return an instance of User. If there is no loggued user then return None
    """
    resu = None
    session = Session.Session(req, lock=0)    
    if session.is_new():
        req.log_error("new session created", apache.APLOG_INFO)   
        init_session(session)
    if session.has_key(LOGGUED_USER_KEY):
        req.log_error("existing session found", apache.APLOG_INFO)
        session.save()        
        resu = session[LOGGUED_USER_KEY]
    else:
        req.log_error("No loggued user found", apache.APLOG_NOTICE)
        # redirect to login        
        util.redirect(req, '/web900/signin.psp')
    return resu


def setLoguedUser(req, user):
    """
    Store an user in session as loggued user
    """
    req.log_error("storing %s in session " % (user.login,), apache.APLOG_INFO)
    session = Session.Session(req, lock=0)
    session[LOGGUED_USER_KEY] = user
    req.log_error("user stored in session", apache.APLOG_DEBUG)    
    session.save()
    req.log_error("session saved", apache.APLOG_DEBUG)


        



def getAttribute(req,name):
    """
    Reccursively search for name field in the request un til req have no previous request.
    If found return the list values for the attribute else None.        
    """    
    try:
         req.form
    except:
        if req.prev:
            return getAttribute(req.prev, name)
        else:
            return None
    else:
        if req.form.has_key(name):
            return req.form.getlist(name)
        elif req.prev:
            return getAttribute(req.prev, name)
        else:
            return None
     